# -*- coding:utf-8 -*-
import json

import requests
from lxml import etree
from utils.HttpUtils import HttpUtils
from utils.AESCrypt import AESCrypt
from pymongo import MongoClient

requests.packages.urllib3.disable_warnings()  # 忽略HTTPS安全警告

class LjyRequest():
    def __init__(self):
        self.headers = {
            'Content_Type': 'application/json',
            'Host': 'tk.lanjiyin.com.cn',
            'Connection': 'Keep-Alive',
            'Accept-Encoding': 'gzip',
            'User-Agent': 'Mozilla/5.0 (Linux; Android 5.1.1; TAS-AN00 Build/HUAWEIMLA-AL10; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/74.0.3729.136 Mobile Safari/537.36'
        }

    def get_contents(self, child_id, tab_key, app_id, app_type, user_id, level, sign):
        postData = {
            'child_id': child_id,
            'tab_key': tab_key, # 'chapter',
            'app_id': app_id,
            'app_type': app_type,
            'user_id': user_id,
            'year': '',
            'is_vod': '0',
            'is_case_vod': '0',
            'level': level, # 1.年份真题   2.真题顺序
            'school_id': '',
            'from_device': '1',
            'idfa': '08:00:27:83:56:5F',
            'secret': '0',
            'token': '2629c17cba739299aa982d3e586611fa',
            'version': '737',
            'moblieinfo': 'TAS-AN00:HUAWEI',
            'is_merge': '1',
            'bundle_id': 'lanjiyin',
            'big_user_id': '1357054',
            'time': '1',
            'sign': sign,
        }
        url = "https://tk.lanjiyin.com.cn/tiku/online/question/list"
        html = HttpUtils.do_request("GET", url, self.headers, postData)
        if html.status_code == 200:
            cryptor = AESCrypt('lanjiyin20500423')
            result_txt = cryptor.aes_decrypt(html.text)
            result_txt = result_txt.replace('result2:', '')
            json_data = json.loads(result_txt)
            if json_data['message'] == '成功':
                for t in json_data['data']['list']:
                    dict_item = dict()
                    dict_item['专业'] = t['chapter_parent_title']
                    dict_item['章节名称'] = t['chapter_title']
                    dict_item['题号'] = t['s_num']
                    dict_item['题目'] = t['title']
                    dict_item['九版还原'] = t['recovery']
                    dict_item['八版还原'] = t['restore']
                    dict_item['答案解析'] = t['explain']
                    dict_item['考点还原'] = t['restoren']
                    dict_item['正确答案'] = t['answer']
                    dict_item['考点大纲'] = t['syllabus']
                    # 题型
                    match t['type']:
                        case "1":
                            dict_item['题型'] = '单选'
                        case "2":
                            dict_item['题型'] = '多选'
                        case "4":
                            dict_item['题型'] = '填空'
                        case "5":
                            dict_item['题型'] = '名词解释'
                        case "6":
                            dict_item['题型'] = '问答'
                    # 单选、多选提取选项
                    if t['type'] in ('1', '2'):
                        for q in t['option']:
                            dict_item['选项_' + q['key']] = q['value']

                    # self.insertItem('蓝基因题库', dict_item)
            else:
                print("============获取失败==============")


    def get_list(self, user_id, app_id, app_type, chapter_title):
        ti_url = f"https://tk.lanjiyin.com.cn/tiku/home_list?user_id={user_id}&app_id={app_id}&app_type={app_type}&tab_key=chapter&year=&is_vod=0&is_case_vod=0&is_high=0&school_id=&max_min_year=&from_device=1&idfa=08%3A00%3A27%3A83%3A56%3A5F&secret=0&token=2629c17cba739299aa982d3e586611fa&version=737&moblieinfo=TAS-AN00%3AHUAWEI&is_merge=1&bundle_id=lanjiyin&big_user_id=1357054&time=1&sign=dc4c7174eefa866a8bbbe028106a19c9"
        html_ti = HttpUtils.do_request("GET", ti_url, self.headers, "")
        json_data_ti = json.loads(html_ti.text)
        for d in json_data_ti['data']:
            dict_data = dict()
            dict_data['专业'] = chapter_title
            dict_data['科目ID'] = d['chapter_id']
            dict_data['科目'] = d['title']
            dict_data['题目数量'] = d['count']
            if d['is_unlock'] == '0':
                dict_data['收费'] = '是'
            else:
                dict_data['收费'] = '否'
            for c in d['list']:
                dict_data['章节ID'] = c['chapter_id']
                dict_data['章节名称'] = c['title']
                dict_data['章节题目数量'] = c['count']
                # self.get_contents(c['chapter_id'], user_id, app_id, app_type, dict_data)
                HttpUtils.dict_to_csv("数量", dict_data)

    def insertItem(tableName, data):
        my_set = db[tableName]
        my_set.insert_one(data)

if __name__ == '__main__':
    conn = MongoClient('127.0.0.1', 27017)
    db = conn["Test"]
    ljy = LjyRequest()
    # 获取章节列表 每换一次科目，sign会更改获取失败
    # ljy.get_list('1732351', 'westernmd_1011', 'zhuanshuo', '西医专硕')
    # ljy.get_list('4411456', 'oral_0322', 'kqkaoyan', '口腔考研')


    # 获取题库
    # ljy.get_contents('38', 'chapter', 'westernmd_1011', 'zhuanshuo', '1732351', '2','eba519a48bfb5fe1ccaa8f7ac620d995')
    ljy.get_contents('49001', 'chapter', 'oral_0322', 'kqkaoyan', '4411456', '2','f37a66d605898710c267b5790f1b104e')
